#!/bin/bash
#生成openvpn客户端

vpn_dir="/etc/openvpn"
#客户端id
client_id=$1
#一个ip段个数
ip_num=64
#ip 网段
ip_gate=$2
#客户端和服务端数据库路径
server_database_path="${vpn_dir}/easy-rsa/3.0/pki"
client_database_path="${vpn_dir}/easy-rsa/3.0/pki"

function usage(){
	echo "please enter client_id and ip_gate,such as $0 192 2"
	exit 1
}

if [ $# != 2 ];then
	usage
fi

function create_vpn(){
	if [ ! -d ${vpn_dir}/config ];then
		mkdir ${vpn_dir}/config
	fi

	#创建文件
	if [ ! -f ${vpn_dir}/config/${ip_gate} ];then
		touch ${vpn_dir}/config/${ip_gate}
	fi
	
	if [ -f ${vpn_dir}/ccd/${client_id} ];then
		echo "File exist!!!Are you want to continue?(yes or no)"
		read answer
		if [ $answer == "yes" ];then
			#删除数据库中原本存在
			sed -i "/${client_id}/d" ${server_database_path}/index.txt
			rm -f ${client_database_path}/private/${client_id}.key ${server_database_path}/reqs/${client_id}.req ${client_database_path}/issued/${client_id}.crt
			rm -f ${vpn_dir}/ccd/${client_id}
			sed -i "/${client_id}/d" ${vpn_dir}/config/${ip_gate}
		else
			#结束
			echo "done" && exit 1
		fi
	fi

	#生成ccd文件
	touch ${vpn_dir}/ccd/${client_id}	
	line_num=`cat ${vpn_dir}/config/${ip_gate} | wc -l`
	echo $line_num
	if [ $line_num -le 64 ];then
		#小于等于64
		let line_num=line_num+1
		
	else
		let line_num=line_num-64
		let ip_gate=ip_gate+1
	fi
	echo $line_num
	openvpn_ip_x=`sed -n "${line_num},1p" ${vpn_dir}/config/openvpnip_manifest`
	openvpn_ip=${openvpn_ip_x/x/${ip_gate}}
	#截取ip最后一位
	openvpnip_suffix=${openvpn_ip##*.}
	#截取ip前缀
	openvpnip_prefix=${openvpn_ip%.*}
	gateway_suffix=`expr ${openvpnip_suffix} + 1`
	#网关
	gateway=${openvpnip_prefix}.${gateway_suffix}

	echo "ifconfig-push $openvpn_ip $gateway" > ${vpn_dir}/ccd/${client_id}	
	echo "${client_id} $openvpn_ip" >> ${vpn_dir}/config/${ip_gate}

	#生成vpn证书
	cd ${vpn_dir}/easy-rsa/3.0/
	if [ ! -d pki ];then
		./easyrsa init-pki
	fi

	
	expect<<EOF
	spawn ./easyrsa build-client-full $client_id nopass
	expect {
		"*phrase:*" {
			send "\r"
			exp_continue
		}		
		"*phrase:*" {
        		send "\r"
        		exp_continue
        	}
		"*ca.key*" {
			send "\r"
			exp_continue
		}
	}
EOF

	#打包客户端配置
	sed "s/vpnclient/${client_id}/g" /etc/openvpn/client.conf > /tmp/client.conf
	if [ ! -d /etc/openvpn/client/${client_id} ];then
		mkdir /etc/openvpn/client/${client_id}
	else
		rm -rf /etc/openvpn/client/${client_id}/* 
	fi
	cd /etc/openvpn/client/${client_id} && cp ${client_database_path}/private/${client_id}.key ${client_database_path}/issued/${client_id}.crt ${client_database_path}/ca.crt /tmp/client.conf /etc/openvpn/easy-rsa/3.0.3/ta.key . && zip -r ../${client_id}.zip * && cd .. && rm -rf ${client_id}
}

create_vpn
